package com.sky.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.common.utils.HttpUtil;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

    public static final  String  Wxlogin = "https://api.weixin.qq.com/sns/jscode2session";
    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
    private UserMapper userMapper;

    @Override
    public User wxlogin(UserLoginDTO userLoginDTO) throws Exception {

        String openid = getOpenid(userLoginDTO);


        // 判断openId是否为空，为空说明登陆异常
        if(openid.isEmpty()){
            throw new Exception(MessageConstant.LOGIN_FAILED);
        }

        // 判断是否为新用户
        User user = userMapper.query(openid);

        // 新用户自动完成注册
        if(user == null){
            user = User.builder().openid(openid).createTime(LocalDateTime.now()).build();
            Long id = userMapper.saveNewUser(user);
        }


        // 返回user对象
        return user;
    }

    private String getOpenid(UserLoginDTO userLoginDTO) {
        // 调用微信接口服务，获取当前用户的openID
        HttpClientUtil httpClientUtil = new HttpClientUtil();
        Map<String, String> map = new HashMap<>();
        map.put("appid",weChatProperties.getAppid());
        map.put("secret",weChatProperties.getSecret());
        map.put("grant_type","authorization_code");
        map.put("js_code", userLoginDTO.getCode());
        String json = httpClientUtil.doGet(Wxlogin, map); // 执行get请求后获得json数据
        JSONObject jsonObject = JSONObject.parseObject(json);
        String openid = jsonObject.getString("openid");
        return openid;
    }
}
